package com.sts.common.utils;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.setting.Setting;
import com.sts.Main;
import com.sts.jdbc.model.JdbcConnectionInfo;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.awt.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author lsl
 * @since 2025年07月16日 19:08
 */
@Slf4j
@Getter
public class ConfigFileUtil {

    private static final String CONFIG_FILE_PATH = System.getProperty("user.home") + FileSystems.getDefault().getSeparator() + ".sts" + FileSystems.getDefault().getSeparator() + "sts.setting";
    public static final Map<String, JdbcConnectionInfo> CONNECTION_INFO_MAP = new LinkedHashMap<>();
    public Font defaultFont = new Font("Maple Mono NF CN", Font.PLAIN, 14);

    public ConfigFileUtil() {
        try {
            log.info("配置文件路径: {}", CONFIG_FILE_PATH);
            Path path = Paths.get(CONFIG_FILE_PATH);

            // 检测配置文件是否存在, 如果不存在就将将默认配置文件下载到指定位置
            checkConfigFileExists(path);

            Setting configSetting = new Setting(CONFIG_FILE_PATH);

            // jdbc 连接信息
            Setting connectionSetting = configSetting.getSetting("connection");
            connectionSetting.forEach((_, v) -> {
                JdbcConnectionInfo jdbcConnectionInfo = JSONUtil.toBean(v, JdbcConnectionInfo.class);
                CONNECTION_INFO_MAP.put(jdbcConnectionInfo.getName(), jdbcConnectionInfo);
            });

            // 字体
            Setting fontSetting = configSetting.getSetting("font");
            String name = fontSetting.get("name");
            String size = fontSetting.get("size");

            Assert.isTrue(StrUtil.isNotBlank(size) &&
                            NumberUtil.isInteger(size) &&
                            Integer.parseInt(size) > 0,
                    "(font-size)字体大小必须为正整数");

            defaultFont = new Font(name, Font.PLAIN, Integer.parseInt(size));
        } catch (IllegalArgumentException e) {
            log.error("{}", e.getMessage(), e);
            JOptionPane.showMessageDialog(
                    Main.rootFrame,
                    "配置文件加载异常: " + e.getMessage(),
                    "启动异常",
                    JOptionPane.ERROR_MESSAGE
            );
            System.exit(1);
        }
    }

    private void checkConfigFileExists(Path path) {
        if (!Files.exists(path)) {
            // 如果配置文件不存在
            try (
                    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("sts.setting");
                    FileOutputStream bufferedOutputStream = new FileOutputStream(CONFIG_FILE_PATH)
            ) {
                byte[] buf = new byte[1024];
                int readLen;
                if (inputStream != null) {
                    while ((readLen = inputStream.read(buf)) != -1) {
                        bufferedOutputStream.write(buf, 0, readLen);
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException("初始化配置文件异常: " + e.getMessage(), e);
            }
        }
    }
}
